package com.jingli.pile.configuration;

import com.jingli.pile.service.PlatformCheckService;
import com.jingli.pile.util.JwtGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class jWTTokenFilter extends OncePerRequestFilter {
    private Logger logger = LoggerFactory.getLogger(jWTTokenFilter.class);
    @Autowired
    private JwtGenerator jwtGenerator;
    @Autowired
    private PlatformCheckService platformCheckService;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        logger.info("进入过滤器:{}",request.getRequestURI());
        final String requestTokenHeader = request.getHeader("Authorization");
        String platformId = null;
        String jwtToken = null;
        if (requestTokenHeader != null && requestTokenHeader.startsWith("Bearer ")) {
            jwtToken = requestTokenHeader.substring(7);
            platformId = jwtGenerator.extractUsername(jwtToken);
        }
        if (platformId != null && SecurityContextHolder.getContext().getAuthentication() == null) {
            UserDetails userDetails = platformCheckService.loadUserByUsername(platformId);

            if (jwtGenerator.validateToken(jwtToken, userDetails)) {
                UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =
                        new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());

                usernamePasswordAuthenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
            }
        }
        chain.doFilter(request, response);
    }
}
